package com.applcn.file.config;

import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * com.applcn.message.config
 * Description:
 *
 * @author: 大妖怪
 * @date: 2020-02-11 12:17
 */
@Component
@Slf4j
public class ApolloConfig implements ApplicationContextAware {
    ApplicationContext applicationContext;

    @Autowired
    private RefreshScope refreshScope;


    @ApolloConfigChangeListener("application-file.yml")
    public void onChange(ConfigChangeEvent changeEvent) {
        boolean eurekaPropertiesChanged = false;
        for (String changedKey : changeEvent.changedKeys()) {
            if (changedKey.startsWith("file")) {
                log.info("===========================apollo refresh start===========================");
                log.info("changedKey:{} value:{}",changedKey,changeEvent.getChange(changedKey));
                ConfigChange configChange = changeEvent.getChange(changedKey);
                configChange.getOldValue();
                eurekaPropertiesChanged = true;
                log.info("===========================apollo refresh end===========================");
                break;
            }
        }
        refreshProperties(changeEvent);
        if (eurekaPropertiesChanged) {
            refreshProperties(changeEvent);
        }
    }
    public void refreshProperties(ConfigChangeEvent changeEvent){
        this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
        refreshScope.refreshAll();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
